package org.hilo.boot.core.logback;

import org.jretty.util.StringSplitUtils;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;

/**
 * 自定义过滤规则
 * @author zollty
 * @since 2018年4月20日
 */
public class PackagePrefixThresholdFilter extends Filter<ILoggingEvent> {

    String prefix;

    Level level;

    String[] prefixes;

    @Override
    public FilterReply decide(ILoggingEvent event) {
        if (!isStarted()) {
            return FilterReply.NEUTRAL;
        }

        if (event.getLevel().isGreaterOrEqual(level) || startWithPrefix(event.getLoggerName())) {
            return FilterReply.NEUTRAL;
        } else {
            return FilterReply.DENY;
        }
    }
    
    protected boolean startWithPrefix(String loggerName) {
        for(String prefix: prefixes) {
            if(loggerName.startsWith(prefix)) {
                return true;
            }
        }
        return false;
    }

    public void start() {
        if (this.prefix != null || this.level != null) {
            prefixes = StringSplitUtils.splitByWholeIgnoreEmpty(prefix, ",");
            super.start();
        }
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public void setLevel(String level) {
        this.level = Level.toLevel(level);
    }

}
